﻿package com.hjb.manager.common.export.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.axis2.databinding.types.soapencoding.Array;
import org.springframework.stereotype.Service;

import com.hjb.common.base.dao.BaseDao;
import com.hjb.manager.common.export.model.ExportColumn;
import com.hjb.manager.common.export.model.ExportTable;
import com.hjb.manager.common.export.service.ExportTableService;


@Service("exportTableService")
public class ExportTableServiceImpl implements ExportTableService{

	@Resource
	private BaseDao baseDao;
	
	private final String[] targetColumn = {"CREATE_USER","CREATE_DATE","UPDATE_USER","UPDATE_DATE"};
	
	@Override
	public ExportTable queryExportTable(String tableName) throws Exception {
			ExportTable et=new ExportTable();
			et.setTableName(tableName);
			List<ExportColumn> columnComentList = baseDao.queryForList("queryColumnComent",tableName);
			Map<Integer,ExportColumn> tempColumns = new HashMap<>();
			for (int i = 0; i < columnComentList.size()-4; i++) {
				if(Arrays.asList(targetColumn).contains(columnComentList.get(i).getColumnName())){
					tempColumns.put(i,columnComentList.get(i));
				}
			}
			if(!tempColumns.isEmpty()){
				int i = columnComentList.size()-4;
				for (Integer oldIndex : tempColumns.keySet()) {
					//找到一个前四位的字段
					for(int j = i; j < columnComentList.size(); j++){
						if(Arrays.asList(targetColumn).contains(columnComentList.get(j).getColumnName())){
							i = j;
							continue;
						}else{
							ExportColumn temp = columnComentList.get(oldIndex);
							columnComentList.set(oldIndex, columnComentList.get(j));
							columnComentList.set(j, temp);
							i = j;
							break;
						}
					}
				}
				for (ExportColumn ec : columnComentList) {
					Map paramMap=new HashMap();
					paramMap.put("tableName", tableName);
					paramMap.put("columnName", ec.getColumnName());
					ExportColumn ci = baseDao.queryForObject("queryColumn",paramMap);
					ec.setColumnLength(ci.getColumnLength());
					ec.setColumnType(ci.getColumnType());
					ec.setNallable(ci.getNallable());
				}
			}
			
			for(ExportColumn each :  columnComentList){
				if("CREATE_USER".equals(each.getColumnName())){
					//{"CREATE_USER","CREATE_TIME","UPDATE_USER","UPDATE_TIME"};
					each.setColumnComment("创建用户");
				}else if("CREATE_TIME".equals(each.getColumnName())){
					each.setColumnComment("创建时间");
				}else if("UPDATE_USER".equals(each.getColumnName())){
					each.setColumnComment("修改用户");
				}else if("UPDATE_TIME".equals(each.getColumnName())){
					each.setColumnComment("修改时间");
				}else if("ID".equals(each.getColumnName())){
					each.setColumnComment("主键标识");
				}
			}
			
			et.setColumns(columnComentList);
			return et;			
	}	
}
